package com.woniuxy.carrental.realm;

import com.woniuxy.carrental.mapper.EmpMapper;
import com.woniuxy.carrental.mapper.PermissionMapper;
import com.woniuxy.carrental.service.EmpService;
import com.woniuxy.carrental.service.PermissionService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

/**
 * @author author
 * @create 2021-09-30 15:22
 */
public class EmpRealm extends AuthorizingRealm {
    @Autowired
    private PermissionMapper permissionMapper;
    @Autowired
    private PermissionService permissionService;
    @Autowired
    private EmpMapper empMapper;
    @Autowired
    private EmpService empService;
    //返回授权信息
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        System.out.println("doGetAuthorizationInfo");

//        simpleAuthenticationInfo.addStringPermission("emp:add");
//        simpleAuthenticationInfo.addStringPermission("emp:delete");
//        simpleAuthenticationInfo.addStringPermission("emp:update");
//        simpleAuthenticationInfo.addStringPermission("emp:select");

        //1. 从 PrincipalCollection 中来获取登录用户的信息
        String account = (String) principals.getPrimaryPrincipal();
        //Integer userId = user.getUserId();
        //2.添加角色和权限
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        List<String> permissions = permissionService.findByAccount(account);
        for (String perm : permissions) {
            //添加权限
            simpleAuthorizationInfo.addStringPermission(perm);
            System.out.println(perm);
        }
        return simpleAuthorizationInfo;
    }
    //返回认证信息
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token)  throws AuthenticationException {
        //token获取用户,去数据库查询
        System.out.println("doGetAuthenticationInfo");
        //AuthenticationToken:参数就是调用login()时传过来的token
        //获取用户登录时输入的用户名
        String principal = (String)token.getPrincipal();
        //去数据库根据用户名获取当前用户的完整对象，
        //数据库查询没有当前用户,Mapper返回null
        System.out.println(1);
        System.out.println(principal);
        if(empService.findByAcc(principal)==null){
            System.out.println(2);
            throw new UnknownAccountException("账号：" + token.getPrincipal() + "不存在");
        }
        Object credentials=empMapper.findPwdByAcc(principal);
        AuthenticationInfo authenticationInfo=
                new SimpleAuthenticationInfo(principal,credentials,this.getName());
        return authenticationInfo;
    }
}
